package com.example.service;

import com.example.entity.Article;
import com.example.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {
        @Autowired
        ArticleRepository articleRepository;

        public List<Article> selectAll(){
            return articleRepository.findAll();
        }


        public Article selectById(Integer id){
            return articleRepository.findById(id).get();
        }

        public Article add(String title,String content){
            Article article = new Article();
            article.setTitle(title);
            article.setContent(content);
            return articleRepository.save(article);
        }

        public Article update(Integer id,String title,String content){
            Article article = new Article();
            article.setId(id);
            article.setTitle(title);
            article.setContent(content);
            return articleRepository.save(article);
        }

        public void deleteById(Integer id){
            if(articleRepository.existsById(id)){
                articleRepository.deleteById(id);
            }
        }

    public Page<Article> findAllByPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return articleRepository.findAll(pageable);

    }



}
